<?php

namespace App\Http\Controllers;

use App\Comment;
use App\Discuss;
use App\Http\Requests;
use App\Parsedown;
use App\Review;
use App\Study;
use App\Studyfav;
use App\Task;
use App\Message;
use App\Solve;
use App\User;
use App\Utils;
use Auth;
use Cache;
use Cookie;
use DB;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Input;
use Log;
use Mail;
use Redirect;
use Reponse;
use View;
use Crypt;
use DateTime;


class rPersonController extends Controller
{
    public function __construct()
    {
        //          $this->middleware('auth');
    }
	public function index(Request $request,$id)
	{
		$id=Utils::url2id($id);
		$user=User::find($id);
		$data=array();
		$data['name']=$user->name;
		$data['score']=$user->score/100;
		$data['step']=$user->step;
		$data['location']=$user->location;
		$data['company']=$user->company;
		$data['avatar']=$user->avatar->url('thumb');
		$data['introduce']=$user->introduce;
		$data['rank']=$user->rank;
		return response()->json($data);

	}
	public function solve(Request $request,$id)
	{
		$id=Utils::url2id($id);
		$user=User::find($id);
		$data=Solve::whereUseridAndType($id,0)->groupby("taskid")->orderby("created_at","desc")->get();
		$arr=array();
		foreach($data as $d)
		{
			$brr=array();
			$brr['taskid']=Utils::id2url($d->taskid);
			$brr['time']=$d->created_at->format("Y-m-d");
			$brr['tasktitle']=Task::find($d->taskid)->title;
			$brr['taskurl']="/task/".$brr['taskid'];
			$arr[]=$brr;
		}
		return response()->json($arr);
	}
	public function discuss(Request $request,$id)
	{
		$id=Utils::url2id($id);
		$user=User::find($id);
		$data=Discuss::whereUserid($id)->orderby("created_at","desc")->get();
		$arr=array();
		foreach($data as $d)
		{
			$brr=array();
			$brr['id']=$d->id;
			$brr['time']=$d->created_at->format("Y-m-d");
			$brr['title']=$d->title;
			$brr['url']="/q/".Utils::id2url($d->id);
			$arr[]=$brr;
		}
		return response()->json($arr);
	}
	public function comment(Request $request,$id)
	{
		$id=Utils::url2id($id);
		$user=User::find($id);
		$data=Comment::whereUseridAndTypeAndDelete($id,1,0)->orderby("created_at","desc")->get();
		$arr=array();
		foreach($data as $d)
		{
			$brr=array();
			$brr['time']=$d->created_at->format("Y-m-d");
			$brr['vote']=$d->vote;
			$brr['id']=$d->id;
			$brr['isvote']=0;
			$brr['comment']=$d->comment;
			$dis=Discuss::find($d->taskid);
			$brr['title']=$dis->title;
			$brr['url']="/q/".Utils::id2url($dis->id);
			$arr[]=$brr;
		}
		return response()->json($arr);
	}
	///////////////////
	public function questions(Request $request, $tag = "all", $type = "new")
    {
        $order = "rtime";
        if ($type == 'hot') $order = "ansnum";
        if ($type == 'unanswered') $order = "created_at";
        $permission = 0;
        if (Auth::check()) {
            $permission = Auth::user()->permission;
        }
        if ($type == "unanswered") {
            if ($tag == "all")
                $questions = Discuss::whereDeleteAndAnsnum(0, 0)->where('permission', '<=', $permission)->orderby("type", "asc")->orderby($order, "desc")->paginate(20);
            else {
				if (Auth::check() && Auth::user()->score >= 100 * 30)
				{
					$questions = Discuss::whereDeleteAndAnsnumAndTag(0, 0, $tag)
						->where('permission', '<=', $permission)
						->where('id', '!=', '284')
						->where('id', '!=', '291')
						->orderby($order, "desc")->paginate(20);
				}
				else
				{
					$questions = Discuss::whereDeleteAndAnsnumAndTag(0, 0, $tag)->where('permission', '<=', $permission)->orderby($order, "desc")->paginate(20);
				}
			}
        } else {
            if ($tag == "all")
                $questions = Discuss::whereDelete(0)->orderby("type", "asc")->where('permission', '<=', $permission)->orderby($order, "desc")->paginate(20);
            else
				if (Auth::check() && Auth::user()->score >= 100 * 30)
					$questions = Discuss::whereDeleteAndTag(0, $tag)
						->where('permission', '<=', $permission)
						->where('id', '!=', '284')
						->where('id', '!=', '291')
						->orderby($order, "desc")->paginate(20);
				else
                	$questions = Discuss::whereDeleteAndTag(0, $tag)->where('permission', '<=', $permission)->orderby($order, "desc")->paginate(20);
        }

        foreach ($questions as $q) {
            $q->user = User::find($q->userid)->name;
			$q->time=$q->created_at->format("Y-m-d");
			$q->url=Utils::id2url($q->id);
            $comment = Comment::whereTypeAndTaskidAndDelete(1, $q->id, 0)->orderBy("created_at", "desc")->take(1)->get();
            if (count($comment) == 0) continue;
            $comment[0]->user = User::find($comment[0]->userid)->name;
			$comment[0]->time=$comment[0]->created_at->format("Y-m-d");
            $q->firstc = $comment[0];
			$q->url=$q->url."#".Utils::id2url($comment[0]->id);

        }
		return response()->json($questions);
	}

    public function rank(Request $request)
    {
        Utils::log($request, 'rank');
        $name = $request->input('name');
        $page = 1;
        $input = $request->all();
        if (isset($input['page']))
            $page = $request->all()['page'];
        if (strlen($name) > 0) {
            $userlist = User::where('score', '>', 0)->where('name', 'like', "%$name%")->orderBy('score', 'desc')->paginate(20);
        } else {
            $userlist = User::where('score', '>', 0)->orderBy('score', 'desc')->paginate(20);
        }

		$data=array();
		$rank=($page-1)*20;
        foreach ($userlist as $k=>$userdata) {
			$rank++;
			$arr=array();
			$arr['name']=$userdata->name;
			$arr['score']=$userdata->score/100;
			$arr['solvenum']=$userdata->solveNum;
			$arr['avatar']=$userdata->avatar->url('thumb');
			$arr['rank']=$rank;
			$arr['url']="/profile/".Utils::id2url($userdata->id);
			$arr['id']=Utils::id2url($userdata->id);
			$arr['medal']="NULL";
			$data[]=$arr;
        }
		$u=$userlist->toArray();
		$ans=array();
		$ans['per_page']=$u['per_page'];
		$ans['current_page']=$u['current_page'];
		$ans['last_page']=$u['last_page'];
		$ans['total']=$u['total'];
		$ans['user']=$data;
		return response()->json($ans);
    }
	public function task(Request $request,$id)
	{
        $id = Utils::url2id($id);
		if($id==143)return;
        $task = Task::select("contributor","id","title","content","material","score")->findOrFail($id);

        $author = User::select("name","email","company","title","location")->find($task->contributor);
        Cookie::queue('这题的答案是oreo', '');
		$au=User::find($task->contributor);
		$author->url=$au->avatar->url("thumb");
		$ans=array();
        $Parsedown = new Parsedown();
        $task->material = $Parsedown->text($task->material);
        if (Auth::check()) {
            $userId = Auth::user()->id;
            $solve = Solve::whereUseridAndTaskidAndType($userId, $id, 0)
                ->get();
            $issolve = true;
            if (count($solve) == 0) $issolve = false;
        } else {
            $issolve = false;
            if (isset($_COOKIE['fs']) && $id == 1) {
                $issolve = true;
            }
        }

if ($id == 25 || $id == 41 || $id == 44 || $id == 72 || $id == 73 || $id == 76 || $id == 80 || $id == 90 || $id == 95 ||$id ==133||$id==140||$id==142) {
            if ($id == 25)
                $rankusers = DB::select('select userid,max(score) as score,max(rscore) as rscore from solves where taskid=25 and type=0 group by userid order by score desc,created_at asc');
            else if ($id == 41)
                $rankusers = DB::select('select userid,min(score) as score,max(rscore) as rscore from solves where taskid=41 and type=0 group by userid order by score asc,created_at asc');
            else if ($id == 72)
                $rankusers = DB::select('select userid,min(score) as score,max(rscore) as rscore from solves where taskid=72 and type=0 group by userid order by score asc,created_at asc');
            else if ($id == 73)
                $rankusers = DB::select('select userid,min(score) as score,max(rscore) as rscore from solves where taskid=73 and type=0 group by userid order by score asc,created_at asc');
            else if ($id == 76)
                $rankusers = DB::select('select userid,min(score) as score,max(rscore) as rscore from solves where taskid=76 and type=0 group by userid order by score asc,created_at asc');
            else if ($id == 44)
                $rankusers = DB::select('select userid,max(score) as score,max(score)*100 as rscore from solves where taskid=44 and type=0 group by userid order by score desc,created_at asc');
            else if ($id == 80)
                $rankusers = DB::select('select userid,max(score) as score,max(score)*100 as rscore from solves where taskid=80 and type=0 group by userid order by score desc,created_at asc');

            else if ($id == 90)
                $rankusers = DB::select('select userid,max(score) as score,max(score) as rscore from solves where taskid=90 and type=0 group by userid order by score desc,created_at asc');

            else if ($id == 95)
                $rankusers = DB::select('select userid,sum(score) as score,max(rscore) as rscore from solves where taskid=95  group by userid order by score desc,created_at asc');
			else if ($id == 133)
                $rankusers = DB::select('select userid,min(score) as score,max(rscore) as rscore from solves where taskid=133 and type=0 group by userid order by score asc,created_at asc');
			else if ($id == 140)
                $rankusers = DB::select('select userid,min(score) as score,max(rscore) as rscore from solves where taskid=140 and type=0 group by userid order by score asc,created_at asc');
			else if ($id == 142)
                $rankusers = DB::select('select userid,min(score) as score,max(rscore) as rscore from solves where taskid=142 and type=0 group by userid order by score asc,created_at asc');


            foreach ($rankusers as $rankuser) {
                $rankuser->name = User::find($rankuser->userid)->name;
            }
			$ans['rank']=$rankusers;
        }

		$ans['task']=$task;
		$ans['author']=$author;
		$ans['issolve']=$issolve;

		return response()->json($ans);

	}
	public function taskcomment(Request $request,$id)
	{
        $id = Utils::url2id($id);
		if($id==143)return;
		$comments = Comment::select("id","comment","userid","created_at","ruserid")->wheretaskidAndDeleteAndType($id, 0, 0)->
        orderBy('updated_at', 'desc')->take(50)->get();
        foreach ($comments as $comment) {
            $user = User::find($comment->userid);
			$comment->time=$comment->created_at->format("Y-m-d");
            $comment->user = User::select("id","name","score","solveNum","rank","introduce")->find($comment->userid);
			$comment->user->id=Utils::id2url($comment->user->id);
            $comment->user->url = $user->avatar->url('thumb');
            $comment->ruser = User::select("id","name","score","solveNum","rank","introduce")->find($comment->ruserid);
			if($comment->ruser!=null)
			{
				$ruser = User::find($comment->ruserid);
				$comment->ruser->id=Utils::id2url($comment->ruser->id);
				$comment->ruser->url = $ruser->avatar->url('thumb');
			}
			if(Auth::check()&&Auth::user()->id==$user->id)
			$comment->candelete=true;
			else $comment->candelete=false;
			$comment->id=Utils::id2url($comment->id);

        }
		return response()->json($comments);
	}



    public function postcomment(Request $request, $id)
    {
        $user = Auth::user();
        $input = $request->all();
        $row = array();
        $row['userid'] = $user->id;
        $row['taskid'] = $id;
        $row['comment'] = $input['comment'];
        $row['ruserid'] = 0;
        if (isset($input['reply'])) {
            $task = Task::find($id);
            Log::info($input['reply']);
            $ruser = User::wherename($input['reply'])->get()->first();
            $row['ruserid'] = $ruser->id;
            $data = Comment::create($row);
            $cid = $data['id'];
            $data1 = array();
            $data1['senderid'] = 1;
            $ruser->msgcnt += 1;
            $ruser->save();
            $data1['receiverid'] = $ruser->id;
            Log::info($input["reply"] . " " . $ruser->id);
            $Parsedown = new Parsedown();
            $content = "**" . $user->name . "**在**" . $task['title'] . '**中回复了你的评论,<a target="_blank" href="/task/' . Utils::id2url($id) . "#comment" . $cid . '">点击查看</a>';
            $data1['content'] = $Parsedown->text($content);
            Message::create($data1);
        } else {
            $data = Comment::create($row);
        }
		$user = User::find($data->userid);
			$data->time=$data->created_at->format("Y-m-d");
            $data->user = User::select("id","name","score","solveNum","rank","introduce")->find($data->userid);
			$data->user->id=Utils::id2url($data->user->id);
            $data->user->url = $user->avatar->url('thumb');
            $data->ruser = User::select("id","name","score","solveNum","rank","introduce")->find($data->ruserid);
			if($data->ruser!=null)
			{
				$ruser = User::find($data->ruserid);
				$data->ruser->id=Utils::id2url($data->ruser->id);
				$data->ruser->url = $ruser->avatar->url('thumb');
			}
			if(Auth::check()&&Auth::user()->id==$user->id)
			$data->candelete=true;
			else $data->candelete=false;
			$data->id=Utils::id2url($data->id);

		return response()->json($data);
    }
	 public function delcomment(Request $request)
    {
        $input = $request->all();
        $comment = Comment::find(Utils::url2id($input["id"]));
		if(Auth::user()->id!=$comment->userid&&Auth::user()->id!=19)return;
        $comment->delete = 1;
        $comment->save();
		$arr=array();
		$arr['suc']=true;
		return response()->json($arr);
    }


    public function qshow(Request $request, $id)
    {

        $id = Utils::url2id($id);
        $dis = Discuss::select("id","title","tag","content","created_at","vote","permission","userid")->findOrFail($id);
        $type = 'discuss';
		$permission = 0;
		if (Auth::check() &&Auth::user()->permission > 0) {
			$permission = Auth::user()->permission;
		}
        if ($permission < $dis->permission) {
            return View::make('errors.404');
        }
        $tasks = Task::whereTitle($dis->tag)->get();
        $dis->vote += 1;
		
        $parser = new ParseDown();
		$comments = Comment::select("score","id","vote","down_vote","userid","comment","created_at","comment_html")->whereTypeAndTaskidAndDelete(1, $id, 0)->get();
		$comments = $comments->sortBy('created_at');
		$dis->ansnum = $comments->count();
		$dis->save();

		if(Auth::check()&&Auth::user()->id==$dis->userid)
			$dis->candelete=true;
		else $dis->candelete=false;
		$dis->id=Utils::id2url($dis->id);
		$dis->time=$dis->created_at->format("Y-m-d");
		$dis->user = User::select("id","name","score","company","title","introduce","rank")->find($dis->userid);
		$dis->user->url=User::find($dis->userid)->avatar->url("thumb");
		$dis->user->id=Utils::id2url($dis->user->id);
		$dis->content=$parser->text($dis->content);

		$count = 1;
		$ca=array();
        foreach ($comments as $c) {
			$c->user = User::select("id","name","score","company","title","introduce","rank")->find($c->userid);
			$c->user->url=User::find($c->userid)->avatar->url("thumb");
			$count += 1;
			$c->comment = $parser->text($c->comment);
            $c->votes = Studyfav::where('type', 1)->where('studyid', $c->id)->get();
            $respons = Comment::whereTypeAndTaskidAndDelete(3, $c->id, 0)->orderBy("created_at", "asc")->get();
			$c->commented = 0;
			$c->id=Utils::id2url($c->id);
			foreach ($respons as $r) {
				$r->user = User::select("id","name","score","company","title","introduce","rank")->find($r->userid);
				$r->user->url=User::find($r->userid)->avatar->url("thumb");
				$r->id=Utils::id2url($r->id);
				$r->user->id=Utils::id2url($r->user->id);
				if ($r->userid == $c->userid) {
					$r->user->name = "(本回复作者)";
				}
                if ($r->ruserid != 0) {
					$r->ruser = User::find($r->ruserid);
					if ($r->ruserid == $c->userid) {
						$r->ruser->name = "(本回复作者)";
					}
				}
				if (Auth::check() && $r->userid == Auth::user()->id && strlen($r->comment) >= 20) {
					$c->commented = 1;
				}
				
			if(Auth::check()&&Auth::user()->id==$r->userid)
			$r->candelete=true;
			else $r->candelete=false;
            }
            $c->respons = $respons;
			$c->time=$c->created_at->format("Y-m-d");
            $c->fav = 0;
            if (Auth::check() && Auth::user()->id != $c->userid) {
                $fav = Studyfav::whereUseridAndStudyidAndType(Auth::user()->id, $c->id, 1)->orderBy('created_at', 'desc')->get()->first();
                if ($fav != null && $fav->vote_type == 0) {
					$c->fav = 1;
				}
				if ($fav != null && $fav->vote_type == 1) {
					$c->fav = -1;
				}
            }

			if(Auth::check()&&Auth::user()->id==$c->userid)
			$c->candelete=true;
			else $c->candelete=false;
			$ca[]=$c;
        }
		$comments = $comments->sortByDesc('score');

		$arr=array();
		$arr["dis"]=$dis;
		$arr['comments']=$ca;
		return response()->json($arr);
    }
public function vote(Request $request)
    {
        $input = $request->all();
        $type = intval($input['type']);
        $vote_type = intval($input['vote_type']);

        if ($vote_type == 0) {
            $factor = 1;
        } else {
            $factor = -1;
        }

        $dataid = Utils::url2id($input['dataid']);
        Log::info(var_export($input, true));
        $fav = $this->studyfav->getFavByUidSidType(Auth::user()->id, $dataid, $type);
        $entity = null;
        if ($type == 2) {
            //文章
            $entity = Article::find($dataid);
        } else if ($type == 1) {
            //讨论区
            $entity = Comment::find($dataid);
            $respons = Comment::whereTypeAndTaskidAndDelete(3, $entity->id, 0)->orderBy("created_at", "asc")->get();
            $commented = 0;
            foreach ($respons as $r) {
                if ($r->userid == Auth::user()->id && strlen($r->comment) >= 20) {
                    $commented = 1;
                }
            }
            if ($commented == 0 && $vote_type != 0) {
                return $entity->score;
            }
        }

        if (Auth::user()->id === $entity->userid) {
            return $entity->score;
        }
        $score = intval(Auth::user()->score / 100);
        if ($fav === null) {
//            not vote
            $fav = array();
            $fav['userid'] = Auth::user()->id;
            $fav['studyid'] = $dataid;
            $fav['type'] = $type;
            $fav['vote_type'] = $vote_type;
            Studyfav::create($fav);
            $entity->score = $entity->score + $factor * $score;
            if ($vote_type == 0) {
                $entity->vote += 1;
            } else {
                $entity->down_vote += 1;
            }
            $entity->save();
        } else {
            if ($fav->type >= 100) {
//                canceled vote
                $fav->type = $fav->type / 100;
                $fav->vote_type = $vote_type;
                $entity->score = $entity->score + $factor * $score;
                if ($vote_type == 0) {
                    $entity->vote += 1;
                } else {
                    $entity->down_vote += 1;
                }
            } else {
//                  voted
                if ($fav->vote_type == $vote_type) {
                    $fav->type = $fav->type * 100;
                    $entity->score = $entity->score - $factor * $score;
                    if ($vote_type == 0) {
                        $entity->vote -= 1;
                    } else {
                        $entity->down_vote -= 1;
                    }
                } else {
                    $fav->vote_type = $vote_type;
                    $entity->score = $entity->score + 2 * $factor * $score;
                    if ($vote_type == 0) {
                        $entity->vote += 1;
                        $entity->down_vote -= 1;
                    } else {
                        $entity->down_vote += 1;
                        $entity->vote -= 1;
                    }
                }
            }
            $fav->save();
            $entity->save();
        }
		$arr=array();
		$arr['fav']=$vote_type;
		$arr['score']=$entity->score;
		return response()->json($arr);
    }

  public function reply(Request $request)
    {
        $parser = new ParseDown();
        $input = $request->all();
		$input['cid']=Utils::url2id($input['cid']);
        $data = array();
        $data['type'] = 1;
        $data['userid'] = Auth::user()->id;
        $data['comment'] = $input['text'];
        $data['comment_html'] = $input['text_html'];
        $data['taskid'] = $input['cid'];
        $c = Comment::create($data);
		$c->user = User::select("id","name","score","company","title","introduce","rank")->find($c->userid);
		$c->user->url=User::find($c->userid)->avatar->url("thumb");
		$c->comment = $parser->text($c->comment);
		$c->votes = Studyfav::where('type', 1)->where('studyid', $c->id)->get();
		$respons = Comment::whereTypeAndTaskidAndDelete(3, $c->id, 0)->orderBy("created_at", "asc")->get();
		$c->commented = 0;
		$c->id=Utils::id2url($c->id);
		$c->score=0;
		foreach ($respons as $r) {
			$r->user = User::select("id","name","score","company","title","introduce","rank")->find($r->userid);
			$r->user->url=User::find($r->userid)->avatar->url("thumb");
			$r->id=Utils::id2url($r->id);
			$r->user->id=Utils::id2url($r->user->id);
				
			if(Auth::check()&&Auth::user()->id==$r->userid)
			$r->candelete=true;
			else $r->candelete=false;
            }
            $c->respons = $respons;
			$c->time=$c->created_at->format("Y-m-d");
            $c->fav = 0;
            if (Auth::check() && Auth::user()->id != $c->userid) {
                $fav = Studyfav::whereUseridAndStudyidAndType(Auth::user()->id, $c->id, 1)->orderBy('created_at', 'desc')->get()->first();
                if ($fav != null && $fav->vote_type == 0) {
					$c->fav = 1;
				}
				if ($fav != null && $fav->vote_type == 1) {
					$c->fav = 2;
				}
            }

			if(Auth::check()&&Auth::user()->id==$c->userid)
			$c->candelete=true;
			else $c->candelete=false;

//        Mail::send('emails.newmsg', ['msg' => "有用户在讨论区写了新的回答"], function ($message) {
//            $message->to('oreo@qlcoder.com', 'John Smith')->subject('Welcome!');
//        });

        $dis = Discuss::find($input['cid']);
        $dis->rtime = time();
        $dis->save();
        $u = User::find($dis->userid);
        $u->msgcnt += 1;
        $u->save();
        $data = array();
        $data['senderid'] = 1;
        $data['receiverid'] = $u->id;
        $data['content'] = Auth::user()->name . "回答了你的问题:『" . $dis->title . "』<a target='_blank' href='/q/" . Utils::id2url($input['cid']) . "'>点击查看</a>";
        $now = Message::create($data);
		return response()->json($c);
    }



}
